// pages/home/home.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    bckcolor:`#a1d2fa`,
    time: 15 * 60,
    percent: 100,
    isRunning: false,
    TaskName: '',
    workTime:0,
    restTime:0,
    record: {}
  },
  // 获取任务title
  textChange(e) {
    this.setData({
      TaskName: e.detail.value
    })
  },
  // 完成任务
  reset() {
    const countDown = this.selectComponent('.control-count-down');
    countDown.reset();
    this.setRecordData('结束')
    this.submitForm(this.data.record)
    this.setData({
      isRunning: false,
      percent: 100,
      TaskName: ''
    })
  },
  // 开始倒计时
  start(event) {
    this.setData({
      isRunning: true,
      time:(event.target.dataset.textname==='工作')?this.data.workTime:this.data.restTime
    })
    this.startCountdown()
    const countDown = this.selectComponent('.control-count-down');
    countDown.start();
    if (!this.data.TaskName) {
      this.setData({
        TaskName: event.target.dataset.textname
      })
    }
    this.setRecordData('开始')
    this.submitForm(this.data.record)
  },

  setRecordData(currentstate){
    this.data.record={
      starttime: this.getstartTime(),
      TaskName_record: this.data.TaskName,
      state: currentstate
    }
  },
  // 获取开始时间
  getstartTime() {
    var timestamp = Date.now();
    // 将时间戳转换为日期对象
    var currenttime = new Date(timestamp).toLocaleString();
return currenttime
  },

  // 倒计时逻辑  
  startCountdown: function () {
    var countdown = this.data.time;
    const intervalId = setInterval(() => {
      countdown--;
      if (countdown <= 0 || this.data.isRunning === false) {
        clearInterval(intervalId);
        wx.showToast({
          title: '倒计时结束',
          icon: 'none',
        });
        this.setData({
          percent: 100
        })
      } else {
        this.setData({
          percent: (countdown * 100 / this.data.time).toFixed(0) // 计算进度值  
        });
      }
    }, 1000);
  },

  // 提交数据
  submitForm(record) {
    var records=wx.getStorageSync('records') || []
    records.unshift(record)
    wx.setStorageSync('records', records)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      workTime: wx.getStorageSync('worktime')*60,
      restTime: wx.getStorageSync('resttime')*60,
      bckcolor:wx.getStorageSync('bckcolor')||''
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})